package com.imut.lagain.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.imut.lagain.entity.User;
import com.imut.lagain.service.IUserService;
import com.imut.lagain.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 情侣控制器
 * 处理情侣相关API请求
 */
@RestController
@RequestMapping("/partners")
@RequiredArgsConstructor
public class PartnerController {
    private static final Logger log = LoggerFactory.getLogger(PartnerController.class);

    private final IUserService userService;
    private final JwtUtil jwtUtil;

    /**
     * 获取当前用户伴侣信息
     * @param authorization JWT令牌
     * @return 伴侣信息
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getPartnerInfo(
            @RequestHeader("Authorization") String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 从JWT中提取用户ID
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            // 获取用户的伴侣信息
            User partnerUser = userService.getPartnerInfo(userId);
            
            if (partnerUser != null) {
                Map<String, Object> partnerInfo = new HashMap<>();
                partnerInfo.put("id", partnerUser.getId());
                partnerInfo.put("nickname", partnerUser.getNickname());
                partnerInfo.put("avatarUrl", partnerUser.getAvatarUrl());
                
                response.put("success", true);
                response.put("data", partnerInfo);
                return ResponseEntity.ok(response);
            }
            
            response.put("success", false);
            response.put("message", "伴侣信息不存在");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取伴侣信息失败", e);
            response.put("success", false);
            response.put("message", "获取伴侣信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 绑定情侣
     * @param authorization JWT令牌
     * @param request 绑定请求
     * @return 绑定结果
     */
    @PostMapping("/bind")
    public ResponseEntity<Map<String, Object>> bindPartner(
            @RequestHeader("Authorization") String authorization,
            @RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String partnerIdStr = request.get("partnerId");
            if (partnerIdStr == null || partnerIdStr.isEmpty()) {
                response.put("success", false);
                response.put("message", "伴侣ID不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            Long partnerId = Long.valueOf(partnerIdStr);
            
            // 解析JWT令牌获取用户ID
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            // 获取当前用户信息
            User currentUser = userService.getById(userId);
            if (currentUser == null) {
                response.put("success", false);
                response.put("message", "当前用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 获取伴侣用户信息
            User partnerUser = userService.getById(partnerId);
            if (partnerUser == null) {
                response.put("success", false);
                response.put("message", "指定的伴侣用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 检查是否已经绑定
            if (currentUser.getPartnerId() != null) {
                response.put("success", false);
                response.put("message", "当前用户已经绑定了伴侣");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (partnerUser.getPartnerId() != null) {
                response.put("success", false);
                response.put("message", "该伴侣用户已经绑定了其他人");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 执行绑定操作
            boolean bindResult = userService.bindPartner(userId, partnerId);
            if (bindResult) {
                Map<String, Object> partnerInfo = new HashMap<>();
                partnerInfo.put("id", partnerId);
                partnerInfo.put("nickname", partnerUser.getNickname());
                partnerInfo.put("avatarUrl", partnerUser.getAvatarUrl());
                
                response.put("success", true);
                response.put("data", partnerInfo);
                response.put("message", "绑定成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "绑定失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            log.error("绑定情侣失败", e);
            response.put("success", false);
            response.put("message", "绑定情侣失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 解除情侣绑定
     * @param authorization JWT令牌
     * @return 解绑结果
     */
    @PostMapping("/unbind")
    public ResponseEntity<Map<String, Object>> unbindPartner(
            @RequestHeader("Authorization") String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 解析JWT令牌获取用户ID
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            // 获取当前用户信息
            User currentUser = userService.getById(userId);
            if (currentUser == null) {
                response.put("success", false);
                response.put("message", "当前用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 检查是否已绑定
            if (currentUser.getPartnerId() == null) {
                response.put("success", false);
                response.put("message", "当前用户未绑定伴侣");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 执行解绑操作
            boolean unbindResult = userService.unbindPartner(userId);
            if (unbindResult) {
                response.put("success", true);
                response.put("message", "解除绑定成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "解除绑定失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            log.error("解除情侣绑定失败", e);
            response.put("success", false);
            response.put("message", "解除绑定失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
}